#! /usr/bin/perl 
use warnings;
use strict;

use warnings;
use strict;
use Getopt::Std;
my %options=();
getopts("f:h:t:o:",\%options);
print $options{o};
open FILE, $options{f} or die "cannot open file $1";
open HEADER, $options{h} or die "cannot open file $1";
open TAIL, $options{t} or die "cannot open file $1";
open FILE2, "> $options{o}" or die " cannot open $options{o}";
my $top_module = 0;
my $marker_start = 0;
my $start_parsing = 0;

while(<HEADER>)
{
		print FILE2 $_;
}
while(<FILE>)
{
# find the markers
		chomp;
		if ($_ =~ /\/\/start_marker/)
		{
				$start_parsing = 1;
		}
		if ($_ =~ /\/\/end_marker/)
		{
				$start_parsing = 0;
		}
		if ($start_parsing == 1)
		{
		my @fields = split;
		if ($fields[0] eq "input")
		{
				$fields[1] =~ s/\;//g ;
				if ($fields[1] eq "clk")
				{
						print FILE2 "clk_in			CELL=PICU_T		SYS_USE=CLOCK "
								. " SYS_IN=clk \n" ;
				}
				else
				{
						if ($fields[1] =~ /\[\d+:0\]/)
						{
								$fields[1] =~ s/\[//g ;
								$fields[1] =~ s/\]//g ;
								chomp($fields[1]);
								my @nums = split /:/, $fields[1];
								my $counter = 0;
								$fields[2] =~ s/;//g ;
								while ($nums[0] >= 0) 
								{
										print FILE2 "$fields[2]_in[$counter]		CELL=PICU_T "
												. " SYS_USE=INPUT " . " SYS_IN=$fields[2]" .
												"[$counter] \n" ;
										$counter++;
										$nums[0]--;
								}

						}
						else
						{
								$fields[1] =~ s/\;//g ;
								print FILE2 "$fields[1]_in		CELL=PICU_T		SYS_USE=INPUT "
										. " SYS_IN=$fields[1] \n" ; 
						}
				}
		}
		elsif ($fields[0] eq "output")
		{
				if ($fields[1] =~ /\[\d+:0\]/)
				{
						$fields[1] =~ s/\[//g ;
						$fields[1] =~ s/\]//g ;
						chomp($fields[1]);
						my @nums = split /:/, $fields[1];
						my $counter = 0;
						$fields[2] =~ s/;//g ;
						while ($nums[0] >= 0) 
						{
								print FILE2 "$fields[2]_out[$counter]		CELL=POC8A_T "
										. " SYS_USE=OUTPUT2 " . " SYS_OUT=$fields[2]" .
										"[$counter] \n" ;
								$counter++;
								$nums[0]--;
						}

				}
				else
				{
						$fields[1] =~ s/\;//g ;
						print FILE2 "$fields[1]_out		CELL=POC8A_T	SYS_USE=OUTPUT2 "
								. " SYS_OUT=$fields[1] \n" ; 
				}
		}
		}
}
while(<TAIL>)
{
		print FILE2 $_;
}
